import md5 from 'md5';
import ServiceInfoManager from './ServiceInfoManager';
import request from './request';
import { getAppIDInfo } from '../config/template';

export default async function gwApiRequest(
  url: string,
  options: IRequestOptions
) {
  const config = getAppIDInfo();
  const appID = config.appId;
  const appSecret = config.appSecret;

  const nowTime = new Date().getTime();
  const token = md5(`${appID}${appSecret}${nowTime}`);

  const requestOptions = {
    ...{
      method: 'POST',
      headers: {
        Authorization: token,
        'X-TIMESTAMP': nowTime,
        'X-Gizwits-Application-Id': appID,
      },
      mode: 'cors'
    },
    ...options
  };
  const gwApplicationApi = await ServiceInfoManager.getGwApplicationUrl();
  console.log('gwApiRequest', gwApplicationApi + url, requestOptions);
  return request(gwApplicationApi + url, requestOptions).then((result) => {
    const { data, success } = result;
    let realSuccess = false;
    let resultCode;
    let resultData: any = {};
    if (success) {
      realSuccess = true;
      resultCode = 200;
      resultData = data;
      console.log(`gwapp result success ${url}`, result);
    } else {
      resultCode = 0; // 请求发生错误
      console.log(`gwapp result error ${url}`, result);
    }
    const compiledResult = {
      code: resultCode,
      message: '',
      success: realSuccess,
      data: resultData,
    };
    return compiledResult;
  });
}
